<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .error {
      color: red;
      font-size: 14px;
    }

    .info {
      color: blue;
      font-size: 14px;
    }
  </style>
</head>

<body>
  <a href="https://www.cnblogs.com/yjf512/archive/2013/02/18/2915171.html">
    参考</a>
  <a href="https://juejin.cn/post/6844903666978127879">参考2</a>
  <br />

  ws address: <input id="wshost" value="ws://192.168.19.107:8001"/> <br />
  用户名: <input id="username" /><br />

  <input type="button" id="connect" value="websocket connect" />
  <input type="button" id="send" value="websocket send=send from client" />
  <input type="button" id="close" value="websocket close" />
  <script src="https://code.jquery.com/jquery-2.2.4.min.js"
    integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

  <div id="error-container"></div>

  <script>
    var socket;

    function writeError(error) {
      logMsg(error, "error")
    }

    function logMsg(msg, cssStyle) {
      let now = new Date()
      line = `<p class="${cssStyle}">${now.toLocaleTimeString()}: ${msg}`
      $("#error-container").append(line)
    }

    function writeInfo(info) {
      logMsg(info, "info")
    }

    $("#connect").click(function (event) {
      // socket = new WebSocket("ws://127.0.0.1:8001");
      let username = $("#username").val()
      if(username.length === 0) {
        alert('请输入用户名')
        return
      }
      socket = new WebSocket($("#wshost").val());
      socket += "?username=" + encodeURIComponent(username)

      socket.onopen = function () {
        writeInfo("Socket has been opened");
      }

      socket.onmessage = function (msg) {
        writeInfo(msg.data);
      }

      socket.onclose = function () {
        writeError("Socket has been closed");
      }
    });

    $("#send").click(function (event) {
      socket.send("send from client");
    });

    $("#close").click(function (event) {
      socket.close();
    })
  </script>
</body>

</html>